package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.ComRecordAdapter;
import flc.ast.bean.MyComRecordBean;
import flc.ast.databinding.ActivityFileDecoBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.UriUtil;

public class FileDecoActivity extends BaseAc<ActivityFileDecoBinding> {

    private ComRecordAdapter recordAdapter;
    private List<MyComRecordBean> listShow = new ArrayList<>();
    private Dialog myDeleteDialog, myRenameDialog;
    private int selPosition;
    private AttachPopupView attachPopupView;
    private EditText editText;

    @Override
    protected int onCreate() {
        return R.layout.activity_file_deco;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);

        mDataBinding.ivFileDecoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvDecoRecord.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        recordAdapter = new ComRecordAdapter();
        mDataBinding.rvDecoRecord.setAdapter(recordAdapter);
        recordAdapter.addChildClickViewIds(R.id.ivSelDocItemEdit);
        recordAdapter.setOnItemChildClickListener(this);
        mDataBinding.ivUpload.setOnClickListener(this);
        //删除弹框
        deleteDialog();
        //重命名弹框
        renameDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivUpload:
                getPermission();
                break;
            //删除弹框
            case R.id.tvDialogDeleteConfirm:
                myDeleteDialog.dismiss();
                delete();
                break;
            case R.id.tvDialogDeleteCancel:
                myDeleteDialog.dismiss();
                break;
            //重命名
            case R.id.tvDialogRenameConfirm:
                String name = editText.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getText(R.string.please_input_video_name));
                    return;
                }
                String suffix = FileUtils.getFileExtension(recordAdapter.getItem(selPosition).getPath());
                if (suffix != "") {
                    FileUtils.rename(recordAdapter.getItem(selPosition).getPath(), name + "." + suffix);
                } else {
                    FileUtils.rename(recordAdapter.getItem(selPosition).getPath(), name);
                }
                myRenameDialog.dismiss();
                editText.setText("");
                getData();
                break;
            case R.id.tvDialogRenameCancel:
                editText.setText("");
                myRenameDialog.dismiss();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        selPosition = position;
        switch (view.getId()) {
            case R.id.ivSelDocItemEdit:
                attachPopupView = new XPopup.Builder(mContext)
                        .hasShadowBg(false)
//                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .isDarkTheme(true)
//                        .popupAnimation(PopupAnimation.NoAnimation) //NoAnimation表示禁用动画
//                        .isCenterHorizontal(true) //是否与目标水平居中对齐
//                        .offsetY(-60)
//                        .offsetX(80)
                        .popupPosition(PopupPosition.Left) //手动指定弹窗的位置
                        .atView(view)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                        .asAttachList(new String[]{getString(R.string.delete), getString(R.string.share), getString(R.string.rename)},
                                new int[]{R.drawable.ashanchu, R.drawable.afenx, R.drawable.achongmm},
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        switch (position) {
                                            case 0:
                                                myDeleteDialog.show();
                                                break;
                                            case 1:
                                                IntentUtil.shareFile(mContext, recordAdapter.getItem(selPosition).getPath());
                                                break;
                                            case 2:
                                                myRenameDialog.show();
                                                break;
                                        }
                                    }
                                }, 0, 0);
                ;
//                }
                attachPopupView.show();
                break;
        }
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        listShow.clear();
        String path = PathUtils.getFilesPathExternalFirst() + Content.MyDecompress;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(new MyComRecordBean(file.getName(), file.getPath()
                        , FileUtils.getSize(file.getPath()), false));
            }
        }
        if (listShow.size() > 0) {
            recordAdapter.setList(listShow);
            mDataBinding.rvDecoRecord.setVisibility(View.VISIBLE);
            mDataBinding.ivDecoRecordNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvDecoRecord.setVisibility(View.GONE);
            mDataBinding.ivDecoRecordNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getPermission() {
        //文件解压
        StkPermissionHelper.reqManageExternalStoragePermission().reqPermissionDesc(getString(R.string.get_deco_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                try {
                    startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 110);
                } catch (android.content.ActivityNotFoundException ex) {
                }
            }
        }).request();
    }

    private void delete() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileUtils.delete(recordAdapter.getItem(selPosition).getPath());
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogDeleteCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogDeleteConfirm);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        // 设置文本及其颜色
        StringBuffer str = new StringBuffer();
        str.append(getString(R.string.delete_tip1));
        str.append("<font color='#FF3838'>" + getString(R.string.delete_tip2) + "</font>");
        str.append(getString(R.string.delete_tip3));
        // 在文本控件中显示
        tip.setText(Html.fromHtml(str.toString(), getImageGetter(), null));
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private Html.ImageGetter getImageGetter() {
        return source -> {
            Drawable drawable = getDrawable(Integer.parseInt(source));
            drawable.setBounds(0, 0, 60, 60);
            return drawable;
        };
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView cancel = inflate.findViewById(R.id.tvDialogRenameCancel);
        TextView comp = inflate.findViewById(R.id.tvDialogRenameConfirm);
        editText = inflate.findViewById(R.id.etDialogFormatRename);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 110) {
                Uri uri = data.getData();
                if (uri == null) {
                    return;
                }
                String selPath = UriUtil.uri2File(uri).getPath();
                if (FileUtils.getFileExtension(selPath).toLowerCase(Locale.ROOT).equals("zip") || FileUtils.getFileExtension(selPath).toLowerCase(Locale.ROOT).equals("rar")) {
                    FileDecoFuncActivity.start(mContext, selPath);
                } else {
                    ToastUtils.showShort(R.string.choose_format_no_support_hint);
                }
            }
        }
    }
}